//
//  AppDelegate.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/23.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import AFNetworking

/**
*  全局变量记录用户账号
*/
var sharedUserAccount  = UserAccount.loadAccount()
/// 切换根控制器通知
let CCSwitchRootVCNotification = "CCSwitchRootVCNotification"
/**
*  @UIApplicationMain 是程序的入口
*/
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        colorSetting()
        setupCache()
        
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        print(path)
        
        print(sharedUserAccount)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        
        window?.makeKeyAndVisible()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: CCSwitchRootVCNotification, object: nil)
        
        return true
    }
    
    /**
        *** 切换控制器
    */
    func switchViewController(n:NSNotification){
        let isMainVC = n.object as! Bool
        window?.rootViewController = isMainVC ? MainViewController():WelcomeViewController()
    }
    /**判断默认的控制器*/
    private func defaultViewController() -> UIViewController{
        if sharedUserAccount != nil {
            return isNewUpdate() ? NewFeatureCollectionViewController():WelcomeViewController()
        }
        return MainViewController()
    }
    private func isNewUpdate() -> Bool{
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
    }
    private func colorSetting(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    /**
    *  设置缓存
    */
    private func setupCache(){
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        let urlCache = NSURLCache(memoryCapacity: 4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil)
        NSURLCache.setSharedURLCache(urlCache)
    }
    /**
    *  注销通知
    */
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: CCSwitchRootVCNotification, object: nil)
    }
}

